package synology.util;

import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Dom
{
	//-------------------------------------------------------------------------
	public static Document loadXML(InputStream strm)
	throws Exception
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = null;
		try
		{
			doc = db.parse(strm);
		}
		catch (SAXException e)
		{
			throw new Exception("Invalid XML document : " + e.getMessage());
		}
		return doc;
	}


	//-------------------------------------------------------------------------
	public static void saveXML(Node doc, OutputStream strm)
	throws Exception
	{
		DOMSource source = new DOMSource(doc);
		StreamResult dest = new StreamResult(strm);
		Transformer storer = TransformerFactory.newInstance().newTransformer();
		storer.setOutputProperty(OutputKeys.INDENT, "yes");
		try
		{
			storer.transform(source, dest);
		}
		catch (Exception e)
		{
			throw new Exception("Invalid XML document : " + e.getMessage());
		}
	}


	//-------------------------------------------------------------------------
	public static void dump(Node node)
	throws Exception
	{
		dump(node, System.out);
	}


	//-------------------------------------------------------------------------
	public static void dump(Node node, OutputStream ostream)
	throws Exception
	{
		DOMSource source = new DOMSource(node);
		StreamResult dest = new StreamResult(ostream);
		Transformer storer = TransformerFactory.newInstance().newTransformer();
		storer.setOutputProperty(OutputKeys.INDENT, "yes");
		storer.setOutputProperty(OutputKeys.METHOD, "xml");
		storer.transform(source, dest);
	}


	//-------------------------------------------------------------------------
	public static Document newDocument()
	throws Exception
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		return db.newDocument();
	}
}
